package com.party.mobile.biz.mall;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.mall.*;
import com.party.core.service.mall.IMallGoodsDetailService;
import com.party.core.service.mall.IMallGoodsFavoriteService;
import com.party.core.service.mall.IMallGoodsService;
import com.party.core.service.mall.IMallGoodsSpecService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.mall.output.MallSiftGoodsOutput;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: Administrator.
 * @Description: 商品业务处理
 * @Date:Created in 2017/8/28 0028 下午 15:56.
 */
@Service
public class MallGoodsBizService {

    @Autowired
    private IMallGoodsService mallGoodsService;
    @Autowired
    private IMallGoodsSpecService mallGoodsSpecService;
    @Autowired
    private IMallGoodsFavoriteService mallGoodsFavoriteService;
    @Autowired
    private IMallGoodsDetailService mallGoodsDetailService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 获取价格显示
     *
     * @param products
     * @return
     */
    public String getPrice(List<MallProduct> products) {
        List<Float> prices = (List<Float>) CollectionUtils.collect(products, input -> {
            MallProduct mm = (MallProduct) input;
            return mm.getPrice();
        });
        Float min = Collections.min(prices); // 最小票价
        Float max = Collections.max(prices); // 最大票价
        if (min.equals(max)) {
            if (min.equals(Float.valueOf("0.0"))) {
                return "0";
            }
            return min.toString();
        } else {
            if (min.equals(Float.valueOf("0.0"))) {
                return "0" + "~" + max.toString();
            }
            return min.toString() + "~" + max.toString();
        }
    }

    /**
     * 获取商品信息
     *
     * @param id: 商品id
     * @return
     */
    public AjaxResult info(String id, String memberId) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(id)) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("商品id不能为空");
            return ajaxResult;
        }

        MallGoodsInfo info = mallGoodsService.info(id);
        if (null == info) {
            throw new BusinessException(PartyCode.IS_NO_DATA, "商品不存在");
        }

        MallGoodsDetail mallGoodsDetail = mallGoodsDetailService.findByGoodsId(id);
        if (mallGoodsDetail != null) {
            String content = mallGoodsDetail.getContent();
            if (StringUtils.isNotEmpty(content)) {
                info.setContent(StringEscapeUtils.unescapeHtml4(content));
            }
        }

        if (StringUtils.isNotEmpty(memberId)) {
            MallGoodsFavorite unique = mallGoodsFavoriteService.getUnique(new MallGoodsFavorite(id, memberId));
            if (unique != null) {
                info.setCollect(true);
            }
        }

        // 开售时间小于当前时间，清除开售时间
        Date openStartTime = info.getOpenStartTime();
        if (openStartTime != null) {
            if (openStartTime.getTime() <= System.currentTimeMillis()) {
                mallGoodsService.clearStartTime(id);
                info.setOpenStartTime(null);
            }
        }
        // 商品的库存小于等于0，更新状态为已售罄
        if (info.getStock() != null && info.getStock() <= 0) {
            if (info.getStock() < 0) {
                mallGoodsService.updateStock(id, 0L);
                info.setStock(0L);
            }
            if (!info.getStatus().equals(MallGoods.STATUS_SELL_OUT)) {
                mallGoodsService.updateStatus(id, MallGoods.STATUS_SELL_OUT);
                info.setStatus(MallGoods.STATUS_SELL_OUT);
            }
        // 商品的库存大于0同时状态为已售罄，更新状态为上架
        } else if (info.getStock() > 0 && info.getStatus().equals(MallGoods.STATUS_SELL_OUT)) {
            mallGoodsService.updateStatus(id, MallGoods.STATUS_UP);
            info.setStatus(MallGoods.STATUS_UP);
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(info);
        return ajaxResult;
    }

    /**
     * 规格选择
     *
     * @param id: 商品id
     * @return
     */
    public AjaxResult specs(String id) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(id)) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("商品id不能为空");
            return ajaxResult;
        }
        MallGoodsSpecOutput mallGoodsSpecOutput = mallGoodsSpecService.specs(id);

        // 处理index
        List<MallGoodsSpecOutput.ProductOut> productList = mallGoodsSpecOutput.getProductList();
        List<MallCategorySiftSpec> specList = mallGoodsSpecOutput.getSpecList();

        if (CollectionUtils.isNotEmpty(specList)) {
            for (int i = 0, j = productList.size(); i < j; i++) {
                MallGoodsSpecOutput.ProductOut productOut = productList.get(i);
                List<Map<String, String>> specList_product = productOut.getSpecList();
                Map<Integer, String> indexMap = Maps.newHashMap();

                product_list:
                for (int ii = 0, jj = specList_product.size(); ii < jj; ii++) {
                    Map<String, String> map_product = specList_product.get(ii);

                    for (int m = 0, n = specList.size(); m < n; m++) {
                        MallCategorySiftSpec mallCategorySiftSpec = specList.get(m);
                        String specId = mallCategorySiftSpec.getId();
                        if (specId.equals(map_product.get("spec_id"))) {
                            List<Map<String, String>> specValues = mallCategorySiftSpec.getSubList();
                            for (int mm = 0, nn = specValues.size(); mm < nn; mm++) {
                                Map<String, String> specValue = specValues.get(mm);
                                if (map_product.get("spec_value_id").equals(specValue.get("id"))) {
                                    indexMap.put(m, map_product.get("spec_value_id"));
                                    continue product_list;
                                }
                            }
                        }
                    }
                }

                StringBuilder index = new StringBuilder("");
                for (int x = 0, y = indexMap.size(); x < y; x++) {
                    index.append(indexMap.get(x)).append(",");
                }
                if (index.length() > 0 && (index.lastIndexOf(",") + 1 == index.length())) {
                    index.deleteCharAt(index.length() - 1);
                }
                productOut.setIndex(index.toString());
            }
        }

        // 查看商品是否有规格产品
        List<MallGoodsSpec> mallGoodsSpecs = mallGoodsSpecService.findByGoodsIdDelFlag(id);
        boolean hasSpec = true;
        if (CollectionUtils.isEmpty(mallGoodsSpecs)) {
            hasSpec = false;
        } else if (mallGoodsSpecs.size() > 1) {
            hasSpec = true;
        } else {
            String specId = mallGoodsSpecs.get(0).getSpecId();
            if (StringUtils.isEmpty(specId)) {
                hasSpec = false;
            } else {
                hasSpec = true;
            }
        }
        // 重新封装输出产品
        Map<String, Object> productOutMap = Maps.newHashMap();
        if (!hasSpec) {
            productList.forEach(product -> {
                Map<String, Object> map = Maps.newHashMap();
                Map<String, Object> sub = Maps.newHashMap();
                sub.put("price", product.getPrice());
                sub.put("id", product.getId());
                sub.put("stock", product.getStock());
                productOutMap.put("unique", sub);
            });
            mallGoodsSpecOutput.setSpecList(null);
        } else {
            productList.forEach(product -> {
                Map<String, Object> map = Maps.newHashMap();
                Map<String, Object> sub = Maps.newHashMap();
                sub.put("price", product.getPrice());
                sub.put("id", product.getId());
                sub.put("stock", product.getStock());
                productOutMap.put(product.getIndex(), sub);
            });
        }
        mallGoodsSpecOutput.setProducts(productOutMap);
        mallGoodsSpecOutput.setProductList(null);
        ajaxResult.setSuccess(true);
        ajaxResult.setData(mallGoodsSpecOutput);
        return ajaxResult;
    }

    /**
     * 通过分类筛选的商品列表
     *
     * @param input
     * @param page
     * @return
     */
    public AjaxResult search(MallCategorySiftGoodsInput input, Page page) {
        AjaxResult ajaxResult = new AjaxResult();
        if (null != input.getSort() && StringUtils.isEmpty(input.getOrder())) {
            input.setOrder("asc");
        }
        List<MallGoods> goods = mallGoodsService.search(input, page);
        List<MallSiftGoodsOutput> outputs = LangUtils.transform(goods, (in) -> {
            MallSiftGoodsOutput output = new MallSiftGoodsOutput();
            BeanUtils.copyProperties(in, output);
            output.setIsHot(false);
            return output;
        });
        ajaxResult.setData(outputs);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 获取用户收藏商品列表
     *
     * @param memberId 用户id
     */
    public List<MallSiftGoodsOutput> getFavoriteList(String memberId, Page page) {
        List<MallGoodsFavorite> favorites = mallGoodsFavoriteService.listPage(new MallGoodsFavorite(memberId), page);
        List<MallSiftGoodsOutput> outputs = LangUtils.transform(favorites, new Function<MallGoodsFavorite, MallSiftGoodsOutput>() {
            @Nullable
            @Override
            public MallSiftGoodsOutput apply(@Nullable MallGoodsFavorite input) {
                MallSiftGoodsOutput output = new MallSiftGoodsOutput();
                if (StringUtils.isEmpty(input.getGoodsId())) {
                    logger.error("收藏数据异常：{}", JSONObject.toJSONString(input));
                    return output;
                }
                MallGoods mallGoods = mallGoodsService.get(input.getGoodsId());
                if (mallGoods == null) {
                    logger.error("收藏数据异常：{}", JSONObject.toJSONString(input));
                    return output;
                }
                output.setId(mallGoods.getId());
                output.setOriginalPrice(mallGoods.getOriginalPrice());
                output.setPic(mallGoods.getPic());
                output.setName(mallGoods.getName());
                output.setPrice(mallGoods.getPrice());
                output.setIsHot(false);
                output.setType(mallGoods.getType());
                return output;
            }
        });
        return outputs;
    }

    /**
     * 加入收藏
     *
     * @param memberId 用户id
     * @param goodsId  商品id
     */
    public void addFavorite(String memberId, String goodsId) {
        MallGoodsFavorite favorite = mallGoodsFavoriteService.getUnique(new MallGoodsFavorite(goodsId, memberId));
        if (favorite != null) {
            throw new BusinessException("该商品已经被收藏");
        }
        favorite = new MallGoodsFavorite();
        favorite.setGoodsId(goodsId);
        favorite.setMemberId(memberId);
        mallGoodsFavoriteService.insert(favorite);
    }
}
